package com.javaweb.admin.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.javaweb.admin.mapper.CGFPMapper;
import com.javaweb.admin.service.ICGFPService;
import com.javaweb.admin.vo.cgfp.CGFPInfo;
import com.javaweb.common.config.CommonConfig;
import com.javaweb.common.config.DataSourceType;
import com.javaweb.common.config.SpecifyDataSource;
import com.javaweb.common.utils.HttpUtils;
import com.javaweb.common.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

import java.util.*;

@Service
public class CGFPServiceImpl implements ICGFPService {

    @Autowired
    CGFPMapper cgfpMapper;

    @Override
    @SpecifyDataSource(value = DataSourceType.SPSunPlatfromDb)
    public List<CGFPInfo> getCGFPList() {
        List<CGFPInfo> list = cgfpMapper.getCGFPList();
        try {
            return list;
        }
        catch(Exception ex)
        {
            return list;
        }
    }

    @Override
    public JsonResult cgfpToBIP(CGFPInfo fp, String token) throws IOException {
        String ocrResult = getOcrResult(token, fp.getUplaodPath().substring(2));
        System.out.println(ocrResult);
        return JsonResult.success();
    }

    public String getOcrResult(String token, String filepath) throws IOException {
        URL url = new URL(CommonConfig.cgfpUrl+filepath);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        InputStream in = connection.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = in.read(buffer)) != -1) {
            out.write(buffer, 0, bytesRead);
        }
        byte[] imageBytes = out.toByteArray();
        out.close();
        in.close();
        connection.disconnect();
        String img = Base64.getEncoder().encodeToString(imageBytes);

        String ocrUrl = CommonConfig.bipDomain+CommonConfig.bipOcrUrl+"?access_token="+token;
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("file", img);
        String ocrResult = HttpUtils.sendPost2(ocrUrl, jsonObject.toJSONString());
        return ocrResult;
    }

    public String getToken(){
        JsonResult jsonResult = new JsonResult();
        long timestamp = System.currentTimeMillis();
        StringBuilder parameterMap = new StringBuilder();
        parameterMap.append("appKey");
        parameterMap.append(CommonConfig.bipAppkey);
        parameterMap.append("timestamp");
        parameterMap.append(String.valueOf(timestamp));
        String signature = getSignature(parameterMap.toString(), CommonConfig.bipAppsecret);
        StringBuilder param = new StringBuilder();
        param.append("appKey=");
        param.append(CommonConfig.bipAppkey);
        param.append("&timestamp=");
        param.append(String.valueOf(timestamp));
        param.append("&signature=");
        param.append(signature);
        String tokenJson = HttpUtils.sendGet(CommonConfig.bipAccessTokenUrl, param.toString());
        String token = JSONObject.parseObject(tokenJson).getJSONObject("data").getString("access_token");
        return token;
    }

    public String getSignature(String data, String secret){
        try {
            // Create HmacSha256 Key
            SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256");

            // Get an instance of Mac object implementing HmacSha256 operation
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(secretKeySpec);

            // Calculate the HMAC value
            byte[] hmacBytes = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
            String hmacHex = Base64.getEncoder().encodeToString(hmacBytes);
            String signature = URLEncoder.encode(hmacHex, "UTF-8");
            return signature;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

}
